package com.pz.cloud.framework.volunteerTeam.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.pz.cloud.framework.base.dao.CommonDao;
import com.pz.cloud.framework.base.expection.CustomRuntimeException;
import com.pz.cloud.framework.base.service.BaseServiceImpl;
import com.pz.cloud.framework.business.stdGroup.entity.OrgStdGroup;
import com.pz.cloud.framework.business.student.entity.Student;
import com.pz.cloud.framework.business.volunteerTeam.entity.VolunteerTeam;
import com.pz.cloud.framework.business.volunteerTeam.entity.VolunteerTeamUser;
import com.pz.cloud.framework.business.volunteerTeam.service.IVolunteerTeamService;
import com.pz.cloud.framework.business.volunteerTeam.service.IVolunteerTeamUserService;
import com.pz.cloud.framework.business.workflow.annotation.Workflow;
import com.pz.cloud.framework.business.workflow.enums.WorkflowEnum;
import com.pz.cloud.framework.model.AbstractSqlBuilder;
import com.pz.cloud.framework.model.SqlBuilder;
import com.pz.cloud.framework.volunteerTeam.callback.VolunteerTeamUserCallback;
import com.pz.cloud.framework.volunteerTeam.mapper.VolunteerTeamUserMapper;
import com.pz.cloud.framework.util.BizUtil;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.handler.DataScopeHandler;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Service
public class VolunteerTeamUserServiceImpl extends BaseServiceImpl<VolunteerTeamUserMapper, VolunteerTeamUser> implements IVolunteerTeamUserService {
    @Autowired
    private CommonDao commonDao;

    @Autowired
    private IVolunteerTeamService volunteerTeamService;

    @Autowired
    private ISysUserService sysUserService;

    @Override
    @Workflow(callback = VolunteerTeamUserCallback.class)
    public boolean save(VolunteerTeamUser entity) {
        boolean flag = false;
        if(StringUtils.isEmpty(entity.getId())){
            String volunteerTeamId = entity.getVolunteerTeamId();
            if (StringUtils.isBlank(volunteerTeamId)) {
                String teamName = entity.getTeamName();
                if (StringUtils.isBlank(teamName)) {
                    throw new CustomRuntimeException("队伍id和队伍名称为空");
                }
                List<VolunteerTeam> teams = volunteerTeamService.findByName(teamName);
                if (CollectionUtils.isEmpty(teams)) {
                    throw new CustomRuntimeException("该队伍不存在");
                }
                volunteerTeamId = teams.get(0).getId();
                entity.setVolunteerTeamId(volunteerTeamId);
            }
            String userId = entity.getUserId();
            if (findByUserIdAndVolunteerTeamId(userId, volunteerTeamId) != null) {
                throw new CustomRuntimeException("该用户申请中或已加入");
            }
            SysUser byId = sysUserService.getById(userId);
            if (byId == null) {
                throw new CustomRuntimeException("用户不存在");
            }
            entity.setRealname(byId.getRealname());
            flag = super.save(entity);
        }else{
            VolunteerTeamUser exisisEntity = super.getById(entity.getId());
            if (exisisEntity != null) {
                flag = super.updateById(entity);
            }
        }
        VolunteerTeam VolunteerTeam = volunteerTeamService.getById(entity.getVolunteerTeamId());
        if (VolunteerTeam != null) {
            entity.getWorkflowModel().setHandlerId(VolunteerTeam.getDirectorId());
        }
        return flag;
    }

    @Override
    public IPage<VolunteerTeamUser> findPage(VolunteerTeamUser entity) {
        AbstractSqlBuilder sqlBuilder = sqlBuilder(entity);
        return commonDao.findPage(sqlBuilder);
    }

    @Override
    public IPage<VolunteerTeamUser> findApplyPage(VolunteerTeamUser entity) {
        AbstractSqlBuilder sqlBuilder = sqlBuilder(entity).append(" and (vu.act_status in (").append(WorkflowEnum.ProcessStatus.流程中.getStatus().toString())
              .append(",").append(WorkflowEnum.ProcessStatus.流程退回.getStatus().toString()).append(") or (vu.act_status=").append(WorkflowEnum.ProcessStatus.未开启.getStatus().toString())
                .append(" and vu.user_id = :userId))").setParms("userId",BizUtil.getUserId());
        return commonDao.findPage(sqlBuilder);
    }

    @Override
    public VolunteerTeamUser findByUserIdAndVolunteerTeamId(String userId, String volunteerTeamId) {
        LambdaQueryWrapper<VolunteerTeamUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(VolunteerTeamUser::getUserId,userId);
        queryWrapper.eq(VolunteerTeamUser::getVolunteerTeamId,volunteerTeamId);
        return getOne(queryWrapper, false);
    }

    private AbstractSqlBuilder sqlBuilder(VolunteerTeamUser entity) {
        DataScopeHandler dataScopeHandler = new DataScopeHandler()
                .setOrgSql("v.id in (select volunteer_team_id from volunteer_team_user where user_id = :userId and del_flag = 0 )").setOrgParms("userId",BizUtil.getUserId())
                .setPersonalSql("vu.user_id = :userId ").setPersonalParms("userId",BizUtil.getUserId())
                .setCustomSql(" or v.id in (SELECT" +
                        " volunteer_team_id FROM volunteer_team_user" +
                        " WHERE user_id = :userId and del_flag = 0 and is_director = 1" +
                        ") ").setCustomParms("userId",BizUtil.getUserId());

        AbstractSqlBuilder sqlBuilder = SqlBuilder.init("select vu.*,v.name team_name,v.director as team_director,s.std_no,s.college,s.major,s.grade,s.clazz,s.entrance_time from ").append(entity.getTableName()).append(" vu")
                .append(" inner join ").append(BizUtil.getTableName(VolunteerTeam.class)).append(" v on vu.volunteer_team_id = v.id and v.del_flag = 0 ")
                .append(" left join ").append(BizUtil.getTableName(Student.class)).append(" s on vu.user_id = s.user_id and s.del_flag = 0 ")
                .append(" where v.act_status >= 10")//正式成立的组织
                .returnType(VolunteerTeamUser.class)
                .page(entity)
                .joinCondition(entity,"vu")
                .filterDataScope(dataScopeHandler)
                .orderBy("vu.id desc");
        String teamName = entity.getTeamName();
        if (StringUtils.isNotBlank(teamName)) {
            sqlBuilder.append(" and v.name like :teamName").setParmsLike("teamName", teamName);
        }
        return sqlBuilder;
    }

}
